package icu.lookyousmileface.nio.zero;

import java.io.IOException;
import java.io.Serializable;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * @author shenj
 * @title: NettyServer
 * @projectName NettyPro
 * @date 2020/12/2 10:47
 */
public class NioServer implements Serializable {

    private static final String host = "127.0.0.1";
    private static final int port = 8899;

    public static void main(String[] args) throws IOException {

        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.socket().bind(new InetSocketAddress(host, port));
        ByteBuffer dataBuffer = ByteBuffer.allocate(4098);

        while (true) {
            SocketChannel socketChannel = serverSocketChannel.accept();
            int readCount = 0;
            while (-1 != readCount) {
                try {
                    //统计读取字节
                    readCount = socketChannel.read(dataBuffer);
                }catch (IOException e){
                    break;
                }
                //可以让dataBuffer复用，使position = 0;mark = -1作废
                dataBuffer.rewind();
            }
        }
    }
}
